import React, {Component} from 'react';
import {withStore} from '../../store/storeUtils';
import {Button, Card, DatePicker, InputItem, List, Modal, SegmentedControl, Toast, WingBlank} from 'antd-mobile';
import {fetchAllCities} from '../../api/city';
import {fetchDevice, updateDevice} from '../../api/deviceApi';
import AddressSelector, {ADDRESS_DELIMITER, asOptions} from "../commons/AddressSelector";
import {createTaskAction, fetchActions, TYPE_TASK_CTL} from '../../api/actionApi';
import MotorSwitch from '../commons/MotorSwitch';
import {formatDate} from '../../util/datetimeUtils';
import './DeviceSetting.less';

const TASK_MAX = 100;

const now = new Date();
now.setSeconds(0);
const TASK_STATE_TABLE = {
    'start': '注册中',
    'fail': '失败',
    'timeout': '超时',
    'success': '成功',
    'conflict': '冲突',
};
const TASK_STATE_LIST = [];
for (const v in TASK_STATE_TABLE) {
    if (!TASK_STATE_TABLE.hasOwnProperty(v)) {
        continue;
    }
    TASK_STATE_LIST.push(TASK_STATE_TABLE[v]);
}

class DeviceSetting extends Component {
    state = {
        cities: [],
        citiesDeep: 1,
        device: {},
        tasks: [],
        taskModalVisible: false,
        taskForm: {
            motor1: 'off',
            motor2: 'off',
            orderTime: now,
        },
        selectedTaskStateIndex: 0,
    };

    componentDidMount() {
        this.deviceId = this.props.match.params.id;
        this.refreshDevice();
        fetchAllCities().then(res => {
            const ctx = [];
            const cols = asOptions(res, ctx, 0);
            this.setState({
                cities: ctx,
                citiesDeep: cols,
            });
        });
        this.refreshActions();
    }

    refreshActions(state) {
        if (!state) {
            const index = this.state.selectedTaskStateIndex;
            const stateName = TASK_STATE_LIST[index];
            for(const key in TASK_STATE_TABLE){
                if(!TASK_STATE_TABLE.hasOwnProperty(key)){
                    continue;
                }
                if(stateName === TASK_STATE_TABLE[key]){
                    state = key;
                }
            }
        }
        const _this = this;
        fetchActions(TYPE_TASK_CTL, state, 1, TASK_MAX).then(res => {
            const {list} = res;
            for (const item of list) {
                item.stateExpect = JSON.parse(item.stateJsonExpect);
            }
            _this.setState({
                tasks: list,
            });
        });
    }

    refreshDevice() {
        fetchDevice(this.deviceId).then(res => {
            this.setState({
                device: res,
            });
        });
    }

    onAddressChange = v => {
        const {device} = this.state;
        const addressCode = v.pop();
        device.address = v.join(ADDRESS_DELIMITER);
        device.addressCode = addressCode;
        this.setState({
            device: device,
        });
    };
    updateDevice = () => {
        const {device} = this.state;
        updateDevice(device).then(res => {
            Toast.show('更新成功', 3, false);
            this.setState({
                device: res,
            });
        })
    };

    showTaskModal(show) {
        this.setState({
            taskModalVisible: show,
        });
    }

    setTaskFormData(field, value) {
        const {taskForm} = this.state;
        taskForm[field] = value;
        if (field === 'orderTime') {
            value.setSeconds(0);
        }
        this.setState({
            taskForm: taskForm,
        });
    }

    doCreateTask = () => {
        const {taskForm} = this.state;
        const deviceId = this.deviceId;
        const params = {
            deviceId: deviceId,
            orderTime: formatDate(taskForm.orderTime),
            targetStatus: {
                motor1: taskForm.motor1,
                motor2: taskForm.motor2,
            }
        };
        const _this = this;
        createTaskAction(params).then(() => {
            _this.showTaskModal(false);
            Toast.show('创建成功', 3, false);
            _this.refreshActions();
        });
    };
    onTaskTypeSelected = e => {
        console.log(e);
        const idx = e.nativeEvent.selectedSegmentIndex;
        const stateStr = TASK_STATE_LIST[idx];
        let state = 'start';
        for (const key in TASK_STATE_TABLE) {
            if (!TASK_STATE_TABLE.hasOwnProperty(key)) {
                continue;
            }
            if (TASK_STATE_TABLE[key] === stateStr) {
                state = key;
            }
        }
        this.setState({
            selectedTaskStateIndex: idx,
        });
        this.refreshActions(state);
    };

    render() {
        const {cities, citiesDeep, device, taskModalVisible, taskForm, tasks, selectedTaskStateIndex} = this.state;
        const displayOrderTime = formatDate(taskForm.orderTime, 'YY-MM-DD HH:mm');
        return (
            <div className="device-setting">
                <List renderHeader="设备信息修改">
                    <InputItem value={device.deviceName}>名称</InputItem>
                    <AddressSelector options={cities} value={device.address || ''} cols={citiesDeep}
                                     onChange={this.onAddressChange} delimiter={ADDRESS_DELIMITER}/>
                </List>
                <WingBlank>
                    <Button type="primary" onClick={this.updateDevice}>保存</Button>
                </WingBlank>
                <List renderHeader={() => '设备任务'}>
                    <List.Item>
                        <SegmentedControl values={TASK_STATE_LIST}
                                          onChange={this.onTaskTypeSelected}
                                          selectedIndex={selectedTaskStateIndex}/>
                    </List.Item>
                    {
                        tasks.map(item => (<Card key={item.id}>
                            <Card.Header title={item.orderTime}/>
                            <Card.Body className="task-content">
                                <div className="line">
                                    <span className="label">电机1:</span>
                                    <span className="value">{item.stateExpect.motor1}</span>
                                </div>
                                <div className="line">
                                    <span className="label">电机2:</span>
                                    <span className="value">{item.stateExpect.motor2}</span>
                                </div>
                                <div className="line">
                                    <span className="label">任务状态:</span>
                                    <span className="value">{item.stateCode}</span>
                                </div>
                            </Card.Body>
                        </Card>))
                    }
                </List>
                <WingBlank>
                    <Button type="primary" onClick={() => this.showTaskModal(true)}>预约任务</Button>
                </WingBlank>
                <Modal visible={taskModalVisible} transparent title="预约任务" footer={[
                    {
                        text: '取消',
                        onPress: () => this.showTaskModal(false)
                    },
                    {
                        text: '确定',
                        onPress: this.doCreateTask,
                    }
                ]}>
                    <List>
                        <DatePicker mode="datetime" title="预约时间" onOk={v => this.setTaskFormData('orderTime', v)}
                                    value={taskForm.orderTime} extra="">
                            <List.Item>
                                时间
                                <List.Item.Brief>
                                    {displayOrderTime}
                                </List.Item.Brief>
                            </List.Item>
                        </DatePicker>
                        <List.Item>
                            <span>电机1</span>
                            <MotorSwitch state={taskForm.motor1} onChange={v => this.setTaskFormData('motor1', v)}/>
                        </List.Item>
                        <List.Item>
                            <span>电机2</span>
                            <MotorSwitch state={taskForm.motor2} onChange={v => this.setTaskFormData('motor2', v)}/>
                        </List.Item>
                    </List>
                </Modal>
            </div>
        );
    }
}

export default withStore(DeviceSetting);